﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPRedisHelper
{
    public class RedisCacheManager
    {
        public static RedisCacheManager Instance = new RedisCacheManager();
        IDatabase db = RedisManager.Manager.GetDatabase(); 
        public string Get(string key)
        {
            return db.StringGet(key);
        }
        public T Get<T>(string key)
        {
            return JsonConvert.DeserializeObject<T>(db.StringGet(key));
        }
        public bool Set<T>(string key,T value,int cacheTime=0)
        {
            string str = JsonConvert.SerializeObject(value);
            if(cacheTime>0)
                return (db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime)));
            else
                return (db.StringSet(key, str));

        }

        public bool Set(string key, object value, int cacheTime=0)
        {
            string str = JsonConvert.SerializeObject(value);
            if(cacheTime>0)
                return (db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime)));
            else
                return (db.StringSet(key, str));
        }
        public bool Set(string key, string value, int cacheTime = 0)
        {
            if (cacheTime > 0)
                return (db.StringSet(key, value, TimeSpan.FromMinutes(cacheTime)));
            else
                return (db.StringSet(key, value));
        }
        public bool IsSet(string key)
        {
            return db.KeyExists(key);
        }
        public void Remove(string key)
        {
            db.KeyDelete(key);
        }
    }
}
